package com.elvish.oda.busin.controller;

import java.util.List;

import org.nutz.lang.Lang;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.elvish.oda.busin.pojo.Role;
import com.elvish.oda.busin.service.RoleService;
import com.elvish.oda.common.pojo.EasyUITableData;
import com.elvish.oda.common.pojo.Page;
import com.elvish.oda.common.pojo.Result;
import com.elvish.oda.common.utils.ResultUtil;

@RestController
public class RoleController {

	@Autowired
	private RoleService roleService;

	/**
	 * 初始化角色表格
	 * 
	 * @param page
	 *            分页信息
	 * @return
	 */
	@PostMapping(value = "/role/initRoleTable")
	public EasyUITableData initRoleTable(Page page) {
		EasyUITableData data = new EasyUITableData();
		List<Role> users = roleService.findAllRoles();
		if (users != null && users.size() != 0) {
			data.setRows(users);
			data.setTotal(users.size());
		}
		return data;
	}

	/**
	 * 角色的CRUD
	 * 
	 * @param role
	 *            角色信息
	 * @param operFlag
	 *            操作符
	 * @param ids
	 *            角色id数组
	 * @return
	 */
	@PostMapping(value = "/role/operRole/{oper}")
	public Result<Role> operRole(Role role, @PathVariable("oper") Integer operFlag,
			@RequestParam(value = "ids[]") String[] ids) {
		Result result = new Result<>();
		try {

			if (operFlag == 1) {
				// 新增
				if (Lang.isEmpty(role.getId())) {
					roleService.save(role);
				}
				// 更新
				else {
					roleService.update(role);
				}
			}
			// 删除
			else if (operFlag == 2) {
				roleService.deleteByIds(ids);
			}
			result = ResultUtil.success();
		} catch (Exception e) {
			result = ResultUtil.fail(-1, "系统异常");
		}
		return result;
	}

	/**
	 * 给用户分配角色
	 * 
	 * @param id
	 *            角色id
	 * @param userId
	 *            用户id
	 * @return
	 */
	@PostMapping(value = "role/chooseRole")
	public Result<Role> chooseRole(Integer id, Integer userId) {
		Result result = new Result<>();
		try {
			roleService.assignUserRole(id, userId);
			result = ResultUtil.success();
		} catch (Exception e) {
			result = ResultUtil.fail(-1, "系统异常");
		}
		return result;
	}

}
